package org.jssvc.opac

import android.content.DialogInterface
import android.content.Intent
import android.os.Bundle
import android.util.Log
import android.view.View
import android.view.ViewGroup
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.widget.SearchView
import androidx.recyclerview.widget.LinearLayoutManager
import cn.bingoogolapple.baseadapter.BGAOnItemChildClickListener
import cn.bingoogolapple.baseadapter.BGAOnRVItemClickListener
import cn.bingoogolapple.refreshlayout.BGANormalRefreshViewHolder
import cn.bingoogolapple.refreshlayout.BGARefreshLayout
import com.blankj.utilcode.util.BarUtils
import com.blankj.utilcode.util.ToastUtils
import com.google.gson.Gson
import com.lzy.okgo.OkGo
import com.lzy.okgo.callback.StringCallback
import com.lzy.okgo.model.Response
import kotlinx.android.synthetic.main.activity_search.*
import org.jssvc.opac.adapter.BookAdapter
import org.jssvc.opac.bean.BookSearchParam
import org.jssvc.opac.bean.BookStore
import org.jssvc.opac.bean.Content
import org.jssvc.opac.bean.SearchResult
import org.jssvc.opac.data.Constant
import org.jssvc.opac.data.DataFormatUtils
import org.jssvc.opac.data.JsoupUtils


class SearchActivity : AppCompatActivity(), BGARefreshLayout.BGARefreshLayoutDelegate,
    BGAOnRVItemClickListener, BGAOnItemChildClickListener {

    var pageNum = 1
    var searchKey = ""
    var mAdapter: BookAdapter? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_search)
        BarUtils.setStatusBarLightMode(this, true)

        initToolBar()

        initSearchView()

        initRefreshLayout()
    }

    private fun initToolBar() {
        setSupportActionBar(tool_bar)
        supportActionBar?.setDisplayHomeAsUpEnabled(true)
        supportActionBar?.setDisplayShowTitleEnabled(false)

        tool_bar.setNavigationOnClickListener {
            onBackPressed()
        }
    }

    private fun initSearchView() {
        search_view.onActionViewExpanded()
        search_view.queryHint = getString(R.string.search_view_hint)
        search_view.isSubmitButtonEnabled = true
        search_view.setOnQueryTextListener(object : SearchView.OnQueryTextListener {
            override fun onQueryTextSubmit(s: String): Boolean {
                searchKey = s
                doSimpleSearch(true)

                search_view.clearFocus()
                return false
            }

            override fun onQueryTextChange(s: String): Boolean {
                return false
            }
        })
    }

    private fun initRefreshLayout() {
        rl_search_refresh.setDelegate(this)
        rl_search_refresh.setRefreshViewHolder(BGANormalRefreshViewHolder(this, true))

        mAdapter = BookAdapter(recycle_view)
        mAdapter?.setOnRVItemClickListener(this)
        mAdapter?.setOnItemChildClickListener(this)

        recycle_view.layoutManager = LinearLayoutManager(this)
        recycle_view.adapter = mAdapter
    }

    override fun onRVItemClick(parent: ViewGroup?, itemView: View?, position: Int) {
        var item = mAdapter?.getItem(position) as Content
        var intent = Intent(this, BookDetailsActivity::class.java)
        intent.putExtra("bean", item)
        startActivity(intent)
    }

    override fun onItemChildClick(parent: ViewGroup?, childView: View?, position: Int) {
        // 解析库存
        var item = mAdapter?.getItem(position) as Content
        getBookStoreInfo(item.marcRecNo!!)
    }

    override fun onBGARefreshLayoutBeginLoadingMore(refreshLayout: BGARefreshLayout?): Boolean {
        doSimpleSearch(false)
        return true
    }

    override fun onBGARefreshLayoutBeginRefreshing(refreshLayout: BGARefreshLayout?) {
        doSimpleSearch(true)
    }

    /**
     * 图书搜索
     */
    private fun doSimpleSearch(isRefreshing: Boolean) {
        if (searchKey == "") {
            rl_search_refresh.endRefreshing()
            rl_search_refresh.endLoadingMore()
            return
        }
        pageNum = if (isRefreshing) 1 else pageNum + 1

        Log.d("DHY__", "searchKey = $searchKey    pageNum = $pageNum")

        val word = BookSearchParam.SearchWordsBean.FieldListBean()
        word.fieldValue = searchKey
        word.fieldCode = ""

        val wordlist = ArrayList<BookSearchParam.SearchWordsBean.FieldListBean>()
        wordlist.add(word)

        val hold = BookSearchParam.SearchWordsBean()
        hold.fieldList = wordlist

        val filters = ArrayList<BookSearchParam.FiltersBean>()
        val limiter = ArrayList<BookSearchParam.LimiterBean>()

        val holdList = ArrayList<BookSearchParam.SearchWordsBean>()
        holdList.add(hold)

        var paramBean = BookSearchParam()
        paramBean.sortField = "relevance"
        paramBean.sortType = "desc"
        paramBean.pageSize = 20
        paramBean.pageCount = pageNum
        paramBean.searchWords = holdList
        paramBean.filters = filters
        paramBean.limiter = limiter

        var json = Gson().toJson(paramBean)
        Log.d("DHY__", "json = $json")

//        var json = getString(R.string.params_search_book, searchKey, pageNum.toString())
        OkGo.post<String>(Constant.api_book_search)
            .upJson(json)
            .execute(object : StringCallback() {
                override fun onSuccess(response: Response<String>?) {
                    val body = response?.body()
                    val item = Gson().fromJson<SearchResult>(body, SearchResult::class.java)

                    if (item.err) {
                        ToastUtils.showShort(item.errMsg)
                    } else {
                        var data2 = item.content as List<Content>
                        if (isRefreshing) {
                            rl_search_refresh.endRefreshing()
                            mAdapter?.data = data2
                            if (data2.isEmpty())
                                ToastUtils.showShort(getString(R.string.search_result_no_data))
                        } else {
                            rl_search_refresh.endLoadingMore()
                            mAdapter?.addMoreData(data2)
                            if (data2.isEmpty())
                                ToastUtils.showShort(getString(R.string.search_result_no_more))
                        }
                    }
                }

                override fun onError(response: Response<String>?) {
                    super.onError(response)
                    rl_search_refresh.endRefreshing()
                    rl_search_refresh.endLoadingMore()
                }
            })
    }

    /**
     * 获取库存
     */
    private fun getBookStoreInfo(marc_no: String) {
        OkGo.get<String>(Constant.api_book_store_info)
            .params("marc_no", marc_no)
            .execute(object : StringCallback() {
                override fun onSuccess(response: Response<String>?) {
                    var html = response?.body().toString()
                    val list = JsoupUtils.parseBookStoreInfo(html)
                    if (list.isNotEmpty()) {
                        showBookStoreDialog(list) // 显示数据
                    }
                }

                override fun onError(response: Response<String>?) {
                    super.onError(response)
                }
            })
    }

    /**
     * 弹框展示库存
     */
    private fun showBookStoreDialog(list: List<BookStore>) {
        AlertDialog.Builder(this@SearchActivity)
            .setTitle(getString(R.string.dialog_book_store_title))
            .setMessage(DataFormatUtils.getBookStoreIntro(list))
            .setPositiveButton(getString(R.string.dialog_book_store_btn)) { dialogInterface: DialogInterface, i: Int ->
                dialogInterface.dismiss()
            }
            .create().show()
    }
}
